﻿Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};

var page = {
    scanInput: "",
    lastInputTime: 0, //上次输入时间
    spanTime: 200, // 输入间隔小于此时间则认为是扫描枪，单位为毫秒
    init: function () {
        //扫码
        $('#btnScan').unbind('click');
        $('#btnScan').on('click', function () {
            imcis.scan.init(function (code,type) {
                if (code == "") {
                    schedule.alert("扫码出错，结果为空!");
                    return;
                }
                //bar 条形码
                pageEvent.setQueryno("queryno", type == "bar" ? "MedRecNO" : "PlacerOrderNO");
                $("#QueryItemValue").val(code);
                pageDataGrid.search();
            }, function (err) {
                schedule.alert(err);
            });
        });

        //查询条件-title支持选择
        $("#dropdown-queryno-item li").unbind('click');
        $("#dropdown-queryno-item li").click(function () {
            var $a = $(this).find("a");
            var $btn = $("#btn-queryno-item");
            $btn.attr("data-id", $a.attr("id"));
            $btn.attr("data-text", $a.text());
            $btn.find(".title").text($a.text());
        });

        $("#dropdown-querydate-item li").unbind('click');
        $("#dropdown-querydate-item li").click(function () {
            var $a = $(this).find("a");
            var $btn = $("#btn-querydate-item");
            if ($a.attr("name") == "queryTimeType") {
                $btn.attr("data-id", $a.attr("id"));
                $btn.attr("data-text", $a.text());
                $btn.find(".title").text($a.text());
            } else {
                pageEvent.getQueryDateMenuItemClick($a.attr("id"));
            }
        });
        //下拉框点击触发事件
        $('#querydateDropdown').unbind('show.bs.dropdown');
        $('#querydateDropdown').on('show.bs.dropdown', function () {
            var $ul = $(this).find('ul');
            var h = $ul.height();
            var mh = $(window).height() - $("#header").height() - $("#search").height() - 30;
            if (h >= mh) {
                $ul.css({ "height": mh + "px", "overflow": " scroll" });
            }
        });

        //下拉多选
        $('.multipleSel').multiselect({
            buttonWidth: "100%",
            dropRight: true,
            checkboxName: 'multiselect[]',
            buttonContainer: '<div class="btn-group btn-multipleSel" />',
            includeSelectAllOption: true, //全选
            selectAllText: '全选',
            enableFiltering: true,
            buttonText: function (options, select) {
                if (options.length === 0) {
                    return '请选择';
                }
                else if (options.length > 3) {
                    return '已选择3个以上选项';
                }
                else {
                    var labels = [];
                    options.each(function () {
                        if ($(this).attr('label') !== undefined) {
                            labels.push($(this).attr('label'));
                        }
                        else {
                            labels.push($(this).html());
                        }
                    });
                    return labels.join(', ') + '';
                }
            },
            onDropdownShown: function (event) {
                var h = $(event.target).find('ul').height();
                var mh = $(window).height() - $("#header").height() - $("#search").height();
                if (h >= mh) {
                    $(event.target).find('ul').css({ "height": mh + "px", "overflow": " scroll"});
                }
            },
            onDropdownHidden: function (event) {
            }
        });

        //查询
        $("#btnSearch").unbind('click');
        $("#btnSearch").click(function () {
            pageDataGrid.search();
        });

        //重置
        $("#btnReset").unbind('click');
        $("#btnReset").click(function () {
            pageEvent.queryReset();
        });

        //存为预设
        $('#userQuerySet button[data-target="#userQuerySetName"]').unbind('click');
        $('#userQuerySet button[data-target="#userQuerySetName"]').click(function () {
            schedule.prompt("存为预设", "请输入预设名", function (val) {
                userQuerySet.saveUserQuerySet(val);
            });
        });

        //自动/手动
        $("#autoFlag").unbind("click");
        $("#autoFlag").click(function () {
            var $this = this;
            if ($($this).attr("isAuto") == "true") {
                clearInterval(userQuerySet.timerQuery);
                userQuerySet.timerQuery = null;
                $('#showTimer').hide();
                $($this).addClass("btn-default").removeClass("btn-danger").attr("isAuto", "false").html("自动");
                //$("#btnSearch").html("查询");
            } else {
                userQuerySet.timerSet();
                $($this).removeClass("btn-default").addClass("btn-danger").attr("isAuto", "true").html("手动");
                //$("#btnSearch").html('查询<span style="font-size:11px;padding-left:2px;">300S</span>');
            }
        });

        //设置定时时间
        $("#showTimer").unbind('click');
        $("#showTimer").click(function () {

            schedule.prompt("存为预设", "请输入定时时间（单位秒）", function (val) {
                userQuerySet.updateTimerTimes(val);
            });
        });

        $("#autoFlag,#showTimer").hide();

        //初始化最近7天的申请单
        pageEvent.getQueryDateMenuItemClick("Today-6");
        userQuerySet.init();
        pageDataGrid.init();
        pageEvent.init();

        //按下INTER键执行查询
        $(document).keydown(function (event) { 
            if ($("#main_container").css("display") != "none") {
                if (event.keyCode == 13) { 
                    if (page.scanInput.length > 1 &&!$('#QueryItemValue').is(":focus")) {
                        $('#QueryItemValue').val(page.scanInput);
                    } 
                    page.scanInput = "";
                    page.lastInputTime = 0;
                    pageDataGrid.search();

                } else {
                    var d = new Date();
                    var keyUpTime = parseInt(d.getTime());
                    if (page.lastInputTime != 0) {
                        if ((keyUpTime - page.lastInputTime) <= page.spanTime) {
                            page.scanInput += event.key;
                        } else {
                            page.scanInput = "";
                            keyUpTime = 0;
                        }
                    } else {
                        page.scanInput += event.key;
                    }
                    page.lastInputTime = keyUpTime;
                }
            } 
            return true;
        });

        //光标定位
        $('#QueryItemValue').focus();
    }
};

var pageDataGrid = {
    sort: 'RequestedDate',
    order: 'desc',
    isOnload: false, //是否加载中
    nowPage: 1, //当前页数
    maxPage: 0,
    rows: 25, //加载行数
    init: function () {
        //根据窗口调整表格高度
        pageEvent.windowResize();
        //生成用户数据
        $('#tbGrid').bootstrapTable({
            method: 'post',
            contentType: "application/x-www-form-urlencoded",
            dataType: "json",
            url: schedule.relativeUrl + "GetScheduleQueryResult?requestType=pad",
            height: pageDataGrid.tableHeight(),//高度调整
            striped: true,  //是否显示行间隔色
            // dataField: "res",//获取数据的别名，先省略，则为你返回的
            pageNumber: 1, //初始化加载第一页，默认第一页
            pagination: false,//是否分页
            queryParamsType: 'limit',
            queryParams: pageDataGrid.queryParams,
            sidePagination: 'server',//在服务器分页
            pageSize: 20,//单页记录数
            pageList: [5, 10, 20, 30],//分页步进值
            showRefresh: false,//刷新按钮
            // showColumns:true,
            clickToSelect: true,//是否启用点击选中行
            toolbarAlign: 'right',
            buttonsAlign: 'right',//按钮对齐方式
            //rowStyle: rowStyle,//通过自定义函数设置行样式
            //showFooter: true,
            locale: 'zh-CN',//中文支持,
            uniqueId: "ObservationUID", 
            columns: [
                //{
                //    checkbox: true
                //},
                {
                    title: '患者姓名',
                    field: 'Name',
                    sortable: false
                },
                {
                    title: '性别',
                    field: 'Sex',
                    sortable: false
                },
                {
                    title: '年龄',
                    field: 'Ages',
                    sortable: true
                },
                {
                    title: '患者ID',
                    field: 'PatientID',
                },
                {
                    title: '病历号',
                    field: 'MedRecNO',
                },
                
                {
                    title: '门诊号',
                    field: 'OutPatientNO',
                },
                {
                    title: '住院号',
                    field: 'InPatientNO',
                },
                
                {
                    title: '病人类型',
                    field: 'PatientClass',
                },
                {
                    title: '就诊科室',
                    field: 'ObservationDeptName'
                },
                {
                    title: '病区',
                    field: 'PointOfCare'
                },
                {
                    title: '床号',
                    field: 'Bed'
                },
                {
                    title: '检查类型',
                    field: 'ServiceSectID'
                },
                {
                    title: '检查项目',
                    field: 'ProcedureName'
                },
                {
                    title: '检查状态',
                    field: 'ResultStatus',
                    formatter: function (value) {
                        if (value == '取消预约') {
                            return '<font color="red" style="font-weight: bolder;">取消预约</font>';
                        }
                        else if (value == '取消检查') {
                            return '<font color="red" style="font-weight: bolder;">取消检查</font>';
                        }
                        else {
                            return value;
                        }
                    }
                }, 
                
                {
                    title: '申请科室',
                    field: 'RequestDeptName'
                },
                {
                    title: '申请医生',
                    field: 'ProviderName'
                },
                {
                    title: '申请时间',
                    field: 'RequestedDate'
                },
                {
                    title: '申请单号',
                    field: 'PlacerOrderNO'
                },
                {
                    title: '卡号',
                    field: 'CardNo',
                },
                {
                    title: '检查号',
                    field: 'AccessionNumber',
                },
                {
                    title: '预约时间',
                    field: 'ScheduleTime',
                    formatter: function (value, row) {
                        return row.ScheduleDate+" "+value; 
                    }
                },
                {
                    title: '预约注意事项',
                    field: 'ScheduleNotice'
                },
                {
                    title: '检查注意事项',
                    field: 'Attention'
                },
                {
                    title: '备注',
                    field: 'RequestMemo'
                }
                
            ],
            onLoadSuccess: function (data) {
                if (data.rows.length == 1) {
                    pagedetail.init(data.rows[0]);
                }
                pageDataGrid.maxPage = data.total;
                if (pageDataGrid.maxPage > pageDataGrid.nowPage) {
                    pageDataGrid.pullDownTip();
                    //滚动事件触发
                    setTimeout(function () {
                        $(".fixed-table-body").bind("scroll", function () {
                            var $this = this;
                            pageDataGrid.pullDownLoad($this);
                        });
                    }, 1000);
                } else if (data.total > 0) {
                    pageDataGrid.pullDownTip("complete");
                }
            },
            onLoadError: function () {
                schedule.alert("数据加载失败！");
            },
            onClickRow: function (row, $element) {
                //var index = $element[0].getAttribute("data-index");
                //pagedetail.init(row, index);
                pagedetail.init(row);
            }
        });
        $('.fixed-table-header').css("background-image", "linear-gradient(#FFF, #f3f3f3)");
       
    },
    tableHeight: function () {
        return $(window).height() - $("#header").outerHeight(true) - $("#search").outerHeight(true) + 8;
    },
    //列表行‘操作’按钮
    AddFunctionAlty: function (value, row, index) {
        return '<button id="TableView" type="button" class="btn btn-default">查看</button>'

    },
    queryParams: function (params) {
        var queryItemCode = $.trim($('#btn-queryno-item').attr("data-id"));
        var queryItemValue = $.trim($('#QueryItemValue').val());
        var pointOfCareID = $('#pointOfCare').val();
        var patientClass = $('#PatientClass').val();
        var serviceSectID = $('#SectID').val();
        var resultStatus = $('#examResultStatus').val();
        var scheduleStartDate = $.trim($('#ScheduleStartDate').val());
        var scheduleEndDate = $.trim($('#ScheduleEndDate').val());
        var dateType = $("#btn-querydate-item").attr("data-id");
        var transportationMode = $("#portCheckbox").is(":checked") ? $("#portCheckbox").val() : "";

        if (pointOfCareID != null) {
            pointOfCareID = pointOfCareID.join(",");
        }
        if (patientClass != null) {
            patientClass = patientClass.join(",");
        }
        if (serviceSectID != null) {
            serviceSectID = serviceSectID.join(",");
        }
        if (resultStatus != null) {
            resultStatus = resultStatus.join(",");
        }

        var queryParams = {
            PointOfCareID: pointOfCareID,
            PatientClass: patientClass,
            ServiceSectID: serviceSectID,
            ResultStatus: resultStatus,
            TransportationMode: transportationMode,
            QueryItemCode: queryItemCode,
            QueryItemValue: queryItemValue, 
            Page: pageDataGrid.nowPage,
            Rows: pageDataGrid.rows,
            Sort: pageDataGrid.sort,
            Order: pageDataGrid.order
        };

        if (scheduleStartDate != "") {
            scheduleStartDate = scheduleStartDate + " 00:00:00";
        }
        if (scheduleEndDate != "") {
            scheduleEndDate = scheduleEndDate + " 23:59:59";
        }
        switch (dateType) {
            case 'RequestedDate':
                queryParams.RequestedStartDate = scheduleStartDate;
                queryParams.RequestedEndDate = scheduleEndDate;
                break;
            case 'ScheduleDate':
                queryParams.ScheduleStartDate = scheduleStartDate;
                queryParams.ScheduleStartDateEnd = scheduleEndDate;
                break;
            default:
                queryParams.ScheduleSaveStartDate = scheduleStartDate;
                queryParams.ScheduleSaveEndDate = scheduleEndDate;
                break;
        }
        if (queryItemValue) {
            queryParams[queryItemCode] = queryItemValue;
        } 

        return queryParams;
    },
    search: function () {
        //查询只查询第一页
        pageDataGrid.nowPage = 1;
        $('#tbGrid').bootstrapTable('refresh', { url: schedule.relativeUrl + "GetScheduleQueryResult?requestType=pad" });
    },
    reload: function () {
        var query = pageDataGrid.queryParams();
        query.Total = query.Page;   //后端分页查询使用
        query.Rows = query.Page * query.Rows;
        query.Page = 1;
        var scrollTop = $($(".fixed-table-body"))[0].scrollTop; //记录当前滚动条位置

        imcis.ajax(schedule.relativeUrl + "GetScheduleQueryResult", { query: query, requestType:"pad" }, true, function (ret) {
            if (ret) {
                $("#tbGrid").bootstrapTable("load", ret.rows);
                $("#tbGrid").bootstrapTable('scrollTo', scrollTop);
                setTimeout(function () {
                    $(".fixed-table-body").bind("scroll", function () {
                        var $this = this;
                        pageDataGrid.pullDownLoad($this);
                    });
                }, 1000);
            } else {
                schedule.alert("重新加载失败！");
            }
        });
    },
    initSearchParams: function (querySeq) {
        for (var key in userQuerySet.list) {
            if (userQuerySet.list[key].querySeq == querySeq) {
                var queryCondition = userQuerySet.list[key].queryCondition;
                if (queryCondition == null) {
                    schedule.alert("默认查询条件初始化失败！");
                    return false;
                }
                pageEvent.setQueryno("queryno", queryCondition.QueryItemCode);
                pageEvent.setQueryno("querydate", queryCondition.QueryTimeType);

                for (var qyId in queryCondition) {
                    var $ele = $("#search").find('[qy-id="' + qyId + '"]');
                    if (["ScheduleSaveStartDate", "RequestedStartDate"].indexOf(qyId) > -1) {
                        $ele = $("#search").find('[qy-id="ScheduleStartDate"]');
                    }
                    if (["ScheduleSaveEndDate", "RequestedEndDate"].indexOf(qyId) > -1) {
                        $ele = $("#search").find('[qy-id="ScheduleStartDateEnd"]');
                    }
                    if ($ele.length == 0)
                        continue;
                    switch ($ele[0].nodeName) {
                        case "INPUT":
                            if ($ele.attr("type") == "date") {
                                $ele.val(pageEvent.dateFullformat(queryCondition[qyId], "yyyy-MM-dd"));
                            } else if ($ele.attr("type") == "checkbox") {
                                if ($.trim(queryCondition[qyId]) == $ele.val())
                                    $ele.prop("checked", true);
                            } else {
                                $ele.val(queryCondition[qyId]);
                            }
                            break;
                        case "SELECT":
                            if ($ele.attr("class").indexOf("multipleSel") > -1) {
                                if (queryCondition[qyId] != null)
                                    $ele.multiselect('select', queryCondition[qyId].split(",")); 

                            } else {
                                $ele.val(queryCondition[qyId]);
                            }
                            break;
                        default:
                            $ele.val(queryCondition[qyId]);
                            break;
                    }
                }
            }
        }
    },
    pullDownLoad: function ($this) {
        if (pageDataGrid.isOnload)
            return;

        if (pageDataGrid.maxPage <= pageDataGrid.nowPage)
            return;

        var $ele = $($this)[0];
        //获取滚动条当前的位置
        var scrollTop = $ele.scrollTop;
        //获取当前可视范围的高度
        var clientHeight = $ele.clientHeight;
        //获取文档完整的高度
        var scrollHeight = Math.max($ele.scrollHeight, $ele.scrollHeight);

        if (scrollTop + clientHeight == scrollHeight) {
            pageDataGrid.nowPage++;
            //此处发起AJAX请求
            pageDataGrid.isOnload = !pageDataGrid.isOnload;
            imcis.ajax(schedule.relativeUrl + "GetScheduleQueryResult?requestType=pad", pageDataGrid.queryParams(), true, function (ret) {
                pageDataGrid.isOnload = !pageDataGrid.isOnload;
                if (ret) {
                    $("#tbGrid").bootstrapTable("append", ret.rows);
                    if (pageDataGrid.maxPage > pageDataGrid.nowPage) {
                        pageDataGrid.pullDownTip();
                        setTimeout(function () {
                            $(".fixed-table-body").scroll(function () {
                                var $this = this;
                                pageDataGrid.pullDownLoad($this);
                            });
                        }, 1000);
                    } else {
                        pageDataGrid.pullDownTip("complete");
                    }
                } else {
                    pageDataGrid.nowPage--;
                    schedule.alert("下拉加载失败！");
                }
            });

        }
    },
    pullDownTip: function (type) {
        var tips = "下拉加载更多数据！";
        if (type == "complete") {
            tips = "已经全部加载完成！";
        }
        $("#tbGrid+.fixed-table-border").css("padding-left","10px").html(tips);
    }
};

var userQuerySet = {
    list: [],
    timerTimes: 300, //定时时间
    timerSeq: null,
    defaultSeq: null,
    timerQuery: null,
    init: function () {
        userQuerySet.loadUserQuerySet();
    },
    addUserSet: function (queryName, ret) {
        var html = '<li id="uqs_' + ret.QuerySeq + '" class="' + (ret.DefaultFlag ? "isDefault" : "")+ '">';   
        html += '<span class="querySetName">' + queryName + '</span>';
        html += '<div class="pull-right">'; 
        html += '<a class="mm-btn-timer icon-time" title="设为定时查询" data-id="' + ret.QuerySeq + '"></a><span class="midline"></span>';
        html += '<a class="mm-btn-default icon-btn-userqueryset_default" title="设为默认" data-id="' + ret.QuerySeq + '"></a><span class="midline"></span>';
        html += '<a class="mm-btn-delete icon-btn-delete" title="删除预设" data-id="' + ret.QuerySeq + '"></a>';
        html += '</div > ';
        html += '</li>';

        $("#userQuerySet ul").append(html);

        if (ret.DefaultFlag) {
            pageEvent.queryReset();
            pageDataGrid.initSearchParams(ret.QuerySeq);
        }

        if (ret.PublicFlag) {
            $('#userQuerySet table .querySetName').css({ 'color': 'rgba(0, 0, 0, 0.847058823529412)', 'text-decoration': 'none' });
            $('#uqs_' + ret.QuerySeq).find('.querySetName').css({ 'color': '#BB2200', 'text-decoration': 'underline' });
            userQuerySet.timerSeq = ret.QuerySeq;
            var queryCondition = userQuerySet.getQueryCondition(ret.QuerySeq);
            if (queryCondition && typeof queryCondition.TimerTimes != "undefined")
                userQuerySet.timerTimes = queryCondition.TimerTimes;
            userQuerySet.timerSet();
        }

        $('#userQuerySet #uqs_' + ret.QuerySeq + ' .mm-btn-default').unbind('click');
        $('#userQuerySet #uqs_' + ret.QuerySeq + ' .mm-btn-default').on('click', userQuerySet.userQuerySetDefault);
        $('#userQuerySet #uqs_' + ret.QuerySeq + ' .mm-btn-delete').unbind('click');
        $('#userQuerySet #uqs_' + ret.QuerySeq + ' .mm-btn-delete').on('click', userQuerySet.userQuerySetDel);
        $('#userQuerySet #uqs_' + ret.QuerySeq + ' .mm-btn-timer').unbind('click');
        $('#userQuerySet #uqs_' + ret.QuerySeq + ' .mm-btn-timer').on('click', userQuerySet.userQuerySetTimer);
        $('#userQuerySet #uqs_' + ret.QuerySeq + ' .querySetName').unbind('click');
        $('#userQuerySet #uqs_' + ret.QuerySeq + ' .querySetName').on('click', function () {
            pageEvent.queryReset();
            pageDataGrid.initSearchParams(ret.QuerySeq);
            pageDataGrid.search();
        });
    },
    saveUserQuerySet: function (queryName) {
        var queryCondition = pageDataGrid.queryParams();
        queryCondition.QueryTimeDuring = "ALL";
        queryCondition.QueryTimeType = $("#btn-querydate-item").attr("data-id");
        queryCondition.QueryTimeDuringText = "所有";
        queryCondition.QueryTimeTypeText = $("#btn-querydate-item").attr("data-text");
        queryCondition.TimerTimes = 300;
        queryCondition = imcis.json.stringify(queryCondition);
        var data = {
            Name: queryName,
            QueryCondition: queryCondition
        };
        imcis.ajax(schedule.relativeUrl + "SaveQueryUserQuerySet", data, true, function (ret) {
            if (ret) {
                ret.QuerySeq = ret.querySeq;
                userQuerySet.addUserSet(queryName, ret);
                userQuerySet.list.push({ querySeq: ret.querySeq, queryCondition: imcis.json.parse(data.QueryCondition) });
                schedule.alert("存为预设成功！");
            } else {
                schedule.alert("存为预设失败！");
            }
        });
    },
    updateTimerTimes: function (timerTimes) {
        var queryCondition = userQuerySet.getQueryCondition(userQuerySet.timerSeq);
        if (!queryCondition)
            schedule.alert("修改定时查询时间失败！");
        queryCondition.TimerTimes = timerTimes;
        var data = {
            QuerySeq: userQuerySet.timerSeq,
            PublicFlag: true,
            DefaultFlag: userQuerySet.defaultSeq == userQuerySet.timerSeq,
            Name: $('#userQuerySet #uqs_' + userQuerySet.timerSeq + ' .querySetName').text(),
            QueryCondition: imcis.json.stringify(queryCondition)
        };
        imcis.ajax(schedule.relativeUrl + "SaveQueryUserQuerySet", data, true, function (ret) {
            if (ret) {
                userQuerySet.timerTimes = timerTimes;
                for (var i = 0; i < userQuerySet.list.length; i++) {
                    if (userQuerySet.list[i].querySeq == userQuerySet.timerSeq) {
                        userQuerySet.list[i].queryCondition.TimerTimes = timerTimes;
                        break;
                    }
                }
                clearInterval(userQuerySet.timerQuery);
                userQuerySet.timerQuery = null;
                userQuerySet.timerSet();
                schedule.alert("修改定时查询时间成功！");
            } else {
                schedule.alert("修改定时查询时间失败！");
            }
        });
    },
    loadUserQuerySet: function () {
        imcis.ajax(schedule.relativeUrl + "GetScheduleUserQuerySet", { queryType: "exam_query_pad" }, false, function (ret) {
            if (ret && ret.length > 0) {
                userQuerySet.list = [];
                for (var i = 0; i < ret.length; i++) {
                    var querySet = ret[i];
                    if (querySet.DefaultFlag)
                        userQuerySet.defaultSeq = querySet.QuerySeq;
                    userQuerySet.list.push({ querySeq: querySet.QuerySeq, queryCondition: imcis.json.parse(querySet.QueryCondition) });
                    userQuerySet.addUserSet(querySet.Name, querySet);
                }
            }
        }, "", function () { });
    },
    //设为默认
    userQuerySetDefault: function () {
        var $item = $(this);
        var id = $item.attr('data-id');
        imcis.ajax(scheduleCommonPath + "SetDefaultUserQuerySet?seq=" + id + "&t=" + imcis.date.now(), {}, true, function (ret) {
            if (ret) {
                $('#userQuerySet ul li').removeClass("isDefault");
                if (ret.result.Result.DefaultFlag) {
                    userQuerySet.defaultSeq = id;
                    $item.parent().parent().addClass("isDefault");
                } else {
                    userQuerySet.defaultSeq = null;
                }
            } else {
                schedule.alert("设为默认失败！");
            }
        });
        event.stopPropagation();
    },
    //删除预设
    userQuerySetDel: function () {
        var $item = $(this);
        var id = $item.attr('data-id');
        schedule.comfirm('确定删除预设?', function () {
            imcis.ajax(scheduleCommonPath + "DeleteUserQuerySet?seq=" + id + "&t=" + imcis.date.now(), {}, true, function (ret) {
                if (ret) {
                    $item.parent().parent().remove();

                    for (var i = 0; i < userQuerySet.list.length; i++) {
                        if (userQuerySet.list[i].querySeq == id) {
                            userQuerySet.list.splice(i, 1);
                            break;
                        }
                    }
                    if (userQuerySet.defaultSeq == id) {
                        userQuerySet.defaultSeq = null;

                    }
                    if (userQuerySet.timerSeq == id) {
                        clearInterval(userQuerySet.timerQuery);
                        userQuerySet.timerQuery = null;
                        $("#autoFlag,#showTimer").hide();
                    }
                    schedule.alert("删除预设成功！");
                } else {
                    schedule.alert("删除预设失败！");
                }
            });
        });
        event.stopPropagation();
    },
    //设为定时查询
    userQuerySetTimer: function () {
        var $item = $(this);
        var id = $item.attr('data-id');
        var setScheduleTimerUserQuerySet = function (seq, callback) {
            imcis.ajax(scheduleCommonPath + "SetScheduleTimerUserQuerySet?seq=" + seq + "&t=" + imcis.date.now(), { queryType: "exam_query_pad" }, true, function (ret) {
                if (ret) {
                    if (callback) {
                        callback();
                        return false;
                    }
                    $('#userQuerySet .querySetName').css({ 'color': 'rgba(0, 0, 0, 0.847058823529412)', 'text-decoration': 'none' });
                    //定时时间恢复成默认值
                    userQuerySet.timerTimes = 300;
                    clearInterval(userQuerySet.timerQuery);
                    userQuerySet.timerQuery = null;
                    if (ret.result.Result.PublicFlag) {
                        userQuerySet.timerSeq = seq;
                        $('#uqs_' + seq).find('.querySetName').css({ 'color': '#BB2200', 'text-decoration': 'underline' });
                        schedule.alert("定时查询设置成功！");
                        var queryCondition = userQuerySet.getQueryCondition(seq);
                        if (queryCondition && typeof queryCondition.TimerTimes != "undefined")
                            userQuerySet.timerTimes = queryCondition.TimerTimes;
                        userQuerySet.timerSet();
                        userQuerySet.timerQueryEvent();
                    } else {
                        userQuerySet.timerSeq = null;
                        $('#showTimer,#autoFlag').hide();
                        $('#showTimer span').text('');
                        schedule.alert("取消定时查询设置成功！");
                    }
                } else {
                    schedule.alert("定时查询设置失败！");
                }
            });
        }

        //只能有一个定时查询，先把旧的取消定时，再更新
        if (userQuerySet.timerSeq != null && userQuerySet.timerSeq != id) {
            setScheduleTimerUserQuerySet(userQuerySet.timerSeq, function () {
                setScheduleTimerUserQuerySet(id);
            });
        } else {
            setScheduleTimerUserQuerySet(id);
        }
        event.stopPropagation();
    },
    //定时设置成功后，设置cookie,开始倒计时，倒计时为0时执行定时搜索，并重新开始计时
    timerSet: function () {
        $('#showTimer span').text(userQuerySet.timerTimes);
        $('#showTimer,#autoFlag').css("display", "inline");
        if (userQuerySet.timerQuery != null) {
            return;
        }
        userQuerySet.timerQuery = setInterval(function () {
            var showTimer = parseInt($('#showTimer span').text());
            if (showTimer > 0) {
                showTimer--;
                $('#showTimer span').text(showTimer);
            } else {
                $('#showTimer span').text(userQuerySet.timerTimes);
                userQuerySet.timerQueryEvent();
                pageDataGrid.initSearchParams(userQuerySet.timerSeq);
                //重新加载并定位到当前位置
                pageDataGrid.reload();
            }
        }, 1000);

    },
    //绑定定时查询时间的相关事件
    timerQueryEvent: function () {
    },
    //根据querySeq获取queryCondition
    getQueryCondition: function (seq) {
        for (var i = 0; i < userQuerySet.list.length; i++) {
            if (userQuerySet.list[i].querySeq == seq)
                return userQuerySet.list[i].queryCondition;
        }
        return false;
    }
};

var pageEvent = {
    //事件初始化
    init: function () {
        //userQuerySet.loadUserQuerySet();
    },
    windowResize: function () {
        $(window).resize(function () {
            //表格根据窗口调整表格高度
            $('#tbGrid').bootstrapTable('resetView', {
                height: pageDataGrid.tableHeight()
            });

            //详细页
            $("#detail_container #detail-body").css("height", pagedetail.detailBodyHeight() + "px");
        });
    },
    multiselectClear: function (id) {
        $("select option").attr("selected", false);
        var $p = $("#" + id).parent();
        //把这个div下的input为checkbox的清空
        $p.find("input[type='checkbox']").each(
            function () { this.checked = false; }
        );
        $p.find(".multiselect-selected-text").text("请选择");
        
    },
    queryReset: function () {
        $("#QueryItemValue").val("");
        //把每一个下拉选项的li的class属性的active去掉
        $(".b-table li").removeClass("active");
        pageEvent.multiselectClear("pointOfCare");
        pageEvent.multiselectClear("examResultStatus");
        pageEvent.multiselectClear("SectID");
        pageEvent.multiselectClear("PatientClass");
        $("#ScheduleStartDate").val("");
        $("#ScheduleEndDate").val("");
        $("#portCheckbox").prop("checked", false);
        
    },
    //时间字符串输出完整格式如：2021-1-1 -> 2021-01-01
    dateFullformat: function (dataStr, type) {
        var arr = dataStr.split(" ");
        var y = arr[0].split("-");
        for (var i = 0; i < y.length; i++) {
            var item = parseInt(y[i]);
            if (item < 10)
                y[i] = "0" + item;
        }
        var date = y[0] + "-" + y[1] + "-" + y[2];
        if (type == "yyyy-MM-dd")
            return date;
        return date + " " + arr[1];
    },
    //点击时间下拉框中的具体时间，为时间控件赋值
    getQueryDateMenuItemClick: function (id) {
        var n, date, endDate; //n星期几减1，date开始时间日期，endDate结束时间日期
        var now = new Date(),
            startTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " 00:00:00",
            endTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " 23:59:59",
            oneDay = 1000 * 60 * 60 * 24,
            oneHour = 1000 * 60 * 60;
        var idArray = id.split('|');
        if (idArray.length == 2) {
            var idStartTime = '', idEndTime = '';
            if (idArray[0].indexOf('-') > -1) {
                idArray0 = idArray[0].split('-');
            } else if (idArray[0].indexOf('+') > -1) {
                idArray0 = idArray[0].split('+');
            }
            if (idArray[1].indexOf('-') > -1) {
                idArray1 = idArray[1].split('-');
            } else if (idArray[1].indexOf('+') > -1) {
                idArray1 = idArray[1].split('+');
            }
            //开始时间
            switch (idArray0[0]) {
                case "Hour":
                    if (idArray[0].indexOf('-') > -1) {
                        date = new Date(now.getTime() - idArray0[1] * oneHour);
                    } else if (idArray[0].indexOf('+') > -1) {
                        date = new Date(now.getTime() + idArray0[1] * oneHour);
                    }
                    startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":00:00";
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    break;
                case "Today":
                    if (idArray[0].indexOf('-') > -1) {
                        date = new Date(now.getTime() - idArray0[1] * oneDay);
                    } else if (idArray[0].indexOf('+') > -1) {
                        date = new Date(now.getTime() + idArray0[1] * oneDay);
                    }
                    startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    break;
                case "Week":
                    if (idArray[0].indexOf("+") > -1) {
                        date = new Date(now.getTime() + (7 * 24 * 3600 * 1000) * idArray0[1]);
                        var week = date.getDay() == 0 ? 7 : date.getDay();
                        date = new Date(date.getTime() - oneDay * (week - 1));
                        startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                    } else if (idArray[0].indexOf("-") > -1) {
                        date = new Date(now.getTime() - (7 * 24 * 3600 * 1000) * idArray0[1]);
                        var week = date.getDay() == 0 ? 7 : date.getDay();
                        date = new Date(date.getTime() - oneDay * (week - 1));
                        startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                    }
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    break;
                case "Month":
                    date = new Date(now);
                    if (idArray[0].indexOf('-') > -1) {
                        date.setMonth(parseInt(date.getMonth()) - idArray0[1]);
                    } else if (idArray[0].indexOf('+') > -1) {
                        date.setMonth(parseInt(date.getMonth()) + parseInt(idArray0[1]));
                    }
                    startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-01 00:00:00";
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    break;
                case "Year":
                    date = new Date(now);
                    if (idArray[0].indexOf('-') > -1) {
                        date.setYear(parseInt(date.getFullYear()) - parseInt(idArray0[1]));
                    } else if (idArray[0].indexOf('+') > -1) {
                        date.setYear(parseInt(date.getFullYear()) + parseInt(idArray0[1]));
                    }
                    startTime = date.getFullYear() + "-01-01 00:00:00";
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    break;
                default:
                    break;
            }

            //结束时间
            switch (idArray1[0]) {
                case "Hour":
                    if (idArray[1].indexOf('-') > -1) {
                        date = new Date(now.getTime() - idArray1[1] * oneHour);
                    } else if (idArray[1].indexOf('+') > -1) {
                        date = new Date(now.getTime() + idArray1[1] * oneHour);
                    }
                    endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":59:59";
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                case "Today":
                    if (idArray[1].indexOf('-') > -1) {
                        date = new Date(now.getTime() - idArray1[1] * oneDay);
                    } else if (idArray[1].indexOf('+') > -1) {
                        date = new Date(now.getTime() + idArray1[1] * oneDay);
                    }
                    endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                case "Week":
                    if (idArray[1].indexOf("+") > -1) {
                        date = new Date(now.getTime() + (7 * 24 * 3600 * 1000) * idArray1[1]);
                        var week = date.getDay() == 0 ? 7 : date.getDay();
                        date = new Date(date.getTime() + oneDay * (7 - week));
                        endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                    } else if (idArray[1].indexOf("-") > -1) {
                        date = new Date(now.getTime() - (7 * 24 * 3600 * 1000) * idArray1[1]);
                        var week = date.getDay() == 0 ? 7 : date.getDay();
                        date = new Date(date.getTime() + oneDay * (7 - week));
                        endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                    }
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                case "Month":
                    date = new Date(now);
                    if (idArray[1].indexOf('-') > -1) {
                        date.setMonth(parseInt(date.getMonth()) - idArray1[1]);
                    } else if (idArray[1].indexOf('+') > -1) {
                        date.setMonth(parseInt(date.getMonth()) + parseInt(idArray1[1]));
                    }
                    var month = date.getMonth();
                    date = new Date(new Date(date.getFullYear(), ++month, 1) - oneDay);
                    endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                case "Year":
                    date = new Date(now);
                    if (idArray[1].indexOf('-') > -1) {
                        date.setYear(parseInt(date.getFullYear()) - parseInt(idArray1[1]));
                    } else if (idArray[1].indexOf('+') > -1) {
                        date.setYear(parseInt(date.getFullYear()) + parseInt(idArray1[1]));
                    }
                    var currentYear = date.getFullYear();
                    date = new Date(new Date(++currentYear, 0, 1) - oneDay);//结束年份的最后一天
                    endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                default:
                    break;
            }
        } else {
            var itemSplit = id.split('-');
            if (itemSplit.length < 2) {
                itemSplit = id.split('+');
            }
            switch (itemSplit[0]) {
                case "All":
                    $("#ScheduleStartDate").val("");
                    $("#ScheduleEndDate").val("");
                    break;
                case "Custom":
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                case "Hour":
                    if (id.indexOf("+") > -1) {
                        date = new Date(now.getTime() + itemSplit[1] * oneHour);
                        endTime = startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                        startTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
                    } else if (id.indexOf("-") > -1) {
                        date = new Date(now.getTime() - itemSplit[1] * oneHour);
                        startTime = startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                        endTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
                    }

                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                case "Today":
                    if (id.indexOf("+") > -1) {
                        date = new Date(now.getTime() + itemSplit[1] * oneDay);
                        endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                    } else if (id.indexOf("-") > -1) {
                        date = new Date(now.getTime() - itemSplit[1] * oneDay);
                        startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                    }
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));

                    break;
                case "Week":
                    n = (now.getDay() == 0 ? 7 : now.getDay()) - 1;
                    if (id.indexOf("+") > -1) {
                        date = new Date(now.getTime() - n * oneDay);
                        endDate = new Date(now.getTime() + (6 - n) * oneDay + parseInt(itemSplit[1]) * 7 * oneDay);
                        startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                        endTime = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate() + " 23:59:59";
                    } else if (id.indexOf("-") > -1) {
                        date = new Date(now.getTime() - (n + parseInt(itemSplit[1]) * 7) * oneDay);
                        endDate = new Date(now.getTime() + (6 - n) * oneDay);
                        startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                        endTime = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate() + " 23:59:59";
                    }
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                case "Month":
                    startTime = now.getFullYear() + "-" + (now.getMonth() + 1 - parseInt(itemSplit[1])) + "-1 00:00:00";
                    var currentMonth = now.getMonth();
                    endDate = new Date(new Date(now.getFullYear(), ++currentMonth, 1) - oneDay); //本月最后一天
                    endTime = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate() + " 23:59:59";
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                case "Year":
                    startTime = (now.getFullYear() - parseInt(itemSplit[1])) + "-1-1 00:00:00"; //itemSplit[1]年前年份的第一天
                    var currentYear = now.getFullYear();
                    endDate = new Date(new Date(++currentYear, 0, 1) - oneDay); //本年最后一天
                    endTime = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate() + " 23:59:59";
                    $('#ScheduleStartDate').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                    $('#ScheduleEndDate').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                    break;
                default:
                    break;
            }
        }
    },
    setQueryno: function (query, id) {
        var $btn = $("#btn-" + query + "-item");
        var $a = $("#dropdown-" + query + "-item #" + id);
        $btn.attr("data-id", $a.attr("id"));
        $btn.attr("data-text", $a.text());
        $btn.find(".title").text($a.text());
    }
};

//详情页
var pagedetail = {
    refresh: false,//关闭是否刷新
    isSignatureLoad: false,
    familyShip: [],
    request: {},
    isNext:true,
    init: function (row) { 
        pagedetail.refresh = false;
        pagedetail.request = row;
        //初始化数据
        pagedetail.initData(row);

        //检查已做
        $("#detail_container .modal-footer .btn-save").unbind('click');
        $("#detail_container .modal-footer .btn-save").click(function () {
            var resultStatus = pagedetail.getExamCompletedResultStatus(row);
            pagedetail.updateExamResultStatus(row, "save", resultStatus);
        });

        //检查未做
        $("#detail_container .modal-footer .btn-backstate").unbind('click');
        $("#detail_container .modal-footer .btn-backstate").click(function () {
            var resultStatus = schedule.GetSysParameterValueByExamRequest({ ServiceSectID: row.ServiceSectID, PatientClass: row.PatientClass }, examUnCompletedResultStatus);
            resultStatus = resultStatus == "" ? "预约完成" : resultStatus;
            pagedetail.updateExamResultStatus(row, "backstate", resultStatus);
        });

        $("#signatureDialogBoxClose").unbind('click').click(pagedetail.close);

        $("#detail_container .modal-footer .btn-save, #detail_container .modal-footer .btn-backstate").hide();

        if ($("#detail_container .modal-footer .btn-save").length != 0) {
            var checkComplete = pagedetail.checkComplete(row);
            if (checkComplete != null) {
                $("#examStateIcon").show();
                if (checkComplete) {    //检查完成
                    $("#detail_container .modal-footer .btn-backstate").show();
                    $("#detail_container .modal-footer .btn-save").hide();
                    $("#examStateIcon_text").html("检查完成");
                } else {    //检查未做
                    $("#detail_container .modal-footer .btn-save").show();
                    $("#detail_container .modal-footer .btn-backstate").hide();
                    $("#examStateIcon_text").html("检查未做");
                }
            } 
        } 
        //弹窗提示信息
        $('[data-toggle="popover"]').popover();

        //显示
        pagedetail.show();

        $("#reuqestInfo").unbind("click").click(function () {
            $(".active").removeClass("active");
            $(this).parent().addClass("active");  
            $("#requestBox").css("display", "block");
            $("#requestBox").animate({ scrollTop: 0 }, 1000);
            $("#detail-table").css("display", "none"); 
            $("#btn-signature-next").show();
            $("#signatureCheckBox").hide();
            $("#btn-signature").hide();
            $("#receiptBox").hide();
        });
        $("#medRecInfo").unbind("click").click(function () {
            $(".active").removeClass("active");
            $(this).parent().addClass("active");  
            $("#detail-table").css("display", "block"); 
            $("#requestBox").css("display", "none");
            pagedetail.loadPatientInfo();
            $("#btn-signature-next").show();
            $("#signatureCheckBox").hide();
            $("#btn-signature").hide();
            $("#receiptBox").hide();
            
        });

        $("#signaturePage").unbind("click").click(function () {   
            if ($("#examStateIcon_text").text() != "签字完成" ||pagedetail.isNext) {
                if (imcis.schedule.docScan.recepitPicture) {
                    $("#receiptPicture").attr("src", imcis.schedule.docScan.recepitPicture);
                    $("#receiptBox").show();
                    $("#receiptBox").animate({ scrollTop: 0 }, 1000);
                } else {
                    $("#receiptBox").hide();
                }
            } else {
                $("#receiptBox").hide();
            }
            $(".active").removeClass("active");
            $(this).parent().addClass("active"); 
            $("#btn-signature").show(); 
            pagedetail.showSignature(); 
        }); 
        $("#btn-signature").unbind("click").click(function () {
            $("#receiptBox").hide();
            pagedetail.showSignature();
            var obj = document.getElementById("ifSignature").contentWindow;
            var btnSignature = obj.document.getElementById("btnSignature");
            btnSignature.click();   
        });

        $("#btn-signature-next").unbind("click").click(function () {  
            if (pagedetail.signatureAllow!="1") {
                schedule.alert("不允许签字，当前检查状态:" + row.ResultStatus);
                return;
            }
            pagedetail.isNext = true;
            $("#signaturePage").click(); 
            pagedetail.isNext = false;
        });
    },
    getExamCompletedResultStatus: function (row) {
        var completedResultStatus = schedule.GetSysParameterValueByExamRequest({ ServiceSectID: row.ServiceSectID, PatientClass: row.PatientClass }, examCompletedResultStatus);
        if ($.trim(completedResultStatus) == "")
            completedResultStatus = "检查完成";
        return completedResultStatus;
    },
    checkComplete: function (row) {
        var completedResultStatus = pagedetail.getExamCompletedResultStatus(row);
        if (row.ResultStatus == completedResultStatus)
            return true;

        var completedByResultStatus = schedule.GetSysParameterValueByExamRequest({ ServiceSectID: row.ServiceSectID, PatientClass: row.PatientClass }, examCompletedByResultStatus);
        if (completedByResultStatus == "") {
            if (row.ResultStatus == "" || row.ResultStatus == "申请完成" || row.ResultStatus == "申请取消" || row.ResultStatus == "预约完成" || row.ResultStatus == "取消预约" || row.ResultStatus == "取消登记" || row.ResultStatus == "取消检查")
                return false;
        } else if (completedByResultStatus.split(",").indexOf(row.ResultStatus) == -1) {
            return false;
        }

        return null;
    },
    detailBodyHeight: function () {
        return $(window).height() - $("#detail_container .detail-head").outerHeight(true) - $("#detail_container .detail-footer").outerHeight(true);
    },
    initData: function (row) {   
        $(".detail-head td").each(function () {
            var headData = $(this).attr("headData");
            if (headData) {
                $(this).text(row[headData]);
            }
        });
        pagedetail.getSchduleRequest(row); 
        pagedetail.patientInfoIsLoad = false;
        imcis.schedule.docScan.recepitQuery = {
            observationUID: row.ObservationUID,
            placerOrderNO: (row.PlacerOrderNO || ''),
            fillerOrderNO: (row.FillerOrderNO || ''),
            printAlone: "alone",
            printQuantity: 1,
            receiptType: "ExamScheduleReceipt"
        }
        pagedetail.signatureAllow = "1";
        var padSignatureResultStatus = $("#hdnPadSignatureResultStatus").val();
        if (padSignatureResultStatus) {
            var allowResultStatus = imcis.schedule.getSysParamValueByServiceSectID(padSignatureResultStatus, row.ServiceSectID);
            if ($.inArray(row.ResultStatus, allowResultStatus.split(',')) == -1) {
                pagedetail.signatureAllow = "0";
            }  
        }

        if (!pagedetail.isSignatureLoad) {
            pagedetail.signature(row);
        }
    },
    loadPatientInfo: function () {
        if (pagedetail.patientInfoIsLoad) {
            return;
        }

        var row = pagedetail.request;
        var setVal = function (id, val) {
            var $td = $('#detail_container td[data-id="' + id + '"]');
            if ($td.length > 0) {
                if (val && val != undefined) {
                    $td.html(val);
                } else {
                    $td.html("");
                }
            }
        };
        row.ChargesWithFlag = "";
        if (row.Charges) {
            var t = "(<span style='color:red'>未缴费</span>)";
            if (row.PaymentsFlag) {
                t = "(已缴费)";
            }
            row.ChargesWithFlag = "<span style='color:#ff9800'>¥" + row.Charges + "</span>" + t;
        }
        row.ScheduleDateTime = "";
        if (row.ScheduleDate) {
            row.ScheduleDateTime = row.ScheduleDate;
            if (row.ScheduleTime) {
                row.ScheduleDateTime = row.ScheduleDate + " " + row.ScheduleTime;
            }
        }

        for (var key in row) {
            setVal(key, row[key]);
        } 
        pagedetail.patientInfoIsLoad = true;
    },
    show: function () {
        $("#main_container").hide();
        $("#detail_container").show();
        $("#detail_container #detail-body").css("height", pagedetail.detailBodyHeight() + "px");
        $("#reuqestInfo").click();
    },
    close: function () {
        $("#main_container").show();
        $("#detail_container").hide();
        pagedetail.isSignatureLoad = false;
        var obj = document.getElementById("ifSignature").contentWindow;
        var btnSave = obj.document.getElementById("btnSave");
        if (btnSave) {
            btnSave.click();  
        } 
        //弹窗提示信息
        $('[data-toggle="popover"]').popover("destroy");
        if (pagedetail.refresh)
            pageDataGrid.reload();  //重新加载并定位到当前位置

        $('#QueryItemValue').focus();
        imcis.schedule.docScan.recepitPicture = "";
        imcis.schedule.docScan.recepitQuery = {};
        $("#signatureAgreeCheck").removeAttr("checked");
        $("#examStateIcon_text").html("");
        $("#requestIframe").hide();
        $("#requestPicture").hide();

        //$("#tbGrid").bootstrapTable("updateRow", {
        //    index: index,
        //    replace: replace,
        //    row: row
        //});
    },
    //更新关检查状态
    updateExamResultStatus: function (row, type, resultStatus) {
        var reason = type == "save" ? "移动查房检查完成操作更新" : "移动查房检查未做操作更新";
        var updateExamResultStatusParams = { observationUIDs: row.ObservationUID, reason: reason, resultStatus: resultStatus };
        imcis.ajax(scheduleAbsolutePath + "UpdateExamResultStatus", updateExamResultStatusParams, true, function (ret) {
            try {
                if (ret.success == 0) {
                    if (type == "save") {
                        $("#detail_container .modal-footer .btn-backstate").show();
                        $("#detail_container .modal-footer .btn-save").hide();
                        $("#examStateIcon_text").html("检查完成");
                    } else {
                        $("#detail_container .modal-footer .btn-backstate").hide();
                        $("#detail_container .modal-footer .btn-save").show();
                        $("#examStateIcon_text").html("检查未做");
                    }
                    pagedetail.refresh = true;
                    schedule.alert("保存成功！");
                } else if (ret.success == -1 && ret.errorMsg == "接口状态变更失败") {
                    schedule.alert(ret.errorMsg);
                }
                else {
                    schedule.alert(ret.msg);
                }
            } catch (e) {
                schedule.alert("前端脚本报错");
            }
        }, "", "", function () {//ajax完成

        });
    }, 
    signature: function (row) {
        var isGetFamilyShip = false;
        if (pagedetail.familyShip.length == 0) {
            isGetFamilyShip = true;
        }
        $("#ifSignature").attr("signatureDataStr", "").attr("familyShip", "").attr("src", ""); 
        imcis.ajax(scheduleAbsolutePath + 'GetSignatureTemplateUploadUrl', { examRequest: row, isGetFamilyShip: isGetFamilyShip }, true, function (ret) {
            var signatureData = [];
            if (ret && ret.success) {
                var signatureUrl = ret.signatureUrl;
                 //签名数据转字符串
                if (ret.signatureData && ret.signatureData.length > 0) {
                    var url = window.location.href.split("ScheduleV2")[0];
                    var signatureDataStr = "";
                    for (var i = 0; i < ret.signatureData.length; i++) {
                        var signatureDataItem = {};
                        if (ret.signatureData[i].ItemName) {
                            signatureDataItem.ItemCode = ret.signatureData[i].ItemCode + ret.signatureData[i].ItemCodeScheme;
                            signatureDataItem.ItemName = ret.signatureData[i].ItemName;
                        } else {
                            continue;
                        }
                        if (ret.signatureData[i].ItemRepresenExt8) {
                            signatureDataItem.filePath = url + ret.signatureData[i].ItemRepresenExt8;
                        } else {
                            continue;
                        }
                        if (ret.signatureData[i].ItemRepresenExt12) {
                            signatureDataItem.patientSignaturePosition = ret.signatureData[i].ItemRepresenExt12;
                        } else {
                            continue;
                        }
                        if (ret.signatureData[i].ItemRepresenExt13) {
                            signatureDataItem.datePosition = ret.signatureData[i].ItemRepresenExt13;
                        }
                        if (ret.signatureData[i].ItemRepresenExt14) {
                            signatureDataItem.doctorSignaturePosition = ret.signatureData[i].ItemRepresenExt14;
                        }
                        if (ret.signatureData[i].ItemRepresenExt15) {
                            signatureDataItem.signatureTimePosition = ret.signatureData[i].ItemRepresenExt15;
                        }
                        if (ret.signatureData[i].ItemRepresenExt16) {
                            signatureDataItem.tellTimePosition = ret.signatureData[i].ItemRepresenExt16;
                        }
                        signatureDataItem.Index = signatureData.length;
                        signatureData.push(signatureDataItem);
                    }
                    if (signatureData.length > 0) {
                        signatureDataStr = encodeURIComponent(JSON.stringify(signatureData));
                    } 
                }
                 
                for (var i = 0; i < ret.familyRelationship.length && isGetFamilyShip; i++) {
                    pagedetail.familyShip.push(ret.familyRelationship[i].ItemName);
                }

                var familyShip = encodeURIComponent(JSON.stringify(pagedetail.familyShip)); 
                $("#ifSignature").attr("signatureDataStr", signatureDataStr).attr("familyShip", familyShip).attr("tellTime", ret.tellTime).attr("doctorSignatureData", ret.doctorSignatureData).attr("src", signatureUrl); 
                pagedetail.isSignatureLoad = true; 
            } else {
                schedule.alert(ret.errorMsg);
            }
        });
    }, 
    showSignature: function () { 
        $("#detail-table").css("display", "none");
        $("#requestBox").css("display", "none");
        $("#ifSignature").css("display", "block");
        $("#signatureCheckBox").show();
        $("#btn-signature-next").hide();
    },
    getSchduleRequest: function (row) { 
        imcis.ajax(imcis.schedule.docScan.absolutePath + 'GetExamRequestImage',
            { examRequest: row, typeCode: "ExamRequest", docType: "申请单" },
            true,
            function (ret) { 
                if (ret && ret.docUrl) { 
                    $("#requestIframe").attr("src", ret.docUrl);
                    $("#requestIframe").show();
                } else if (ret && ret.imgUrl) {
                    $("#requestPicture").attr("src", ret.imgUrl);
                    $("#requestPicture").show();
                } else {
                    $("#medRecInfo").click(); //获取申请单失败则显示门诊信息 
                }
            },
            function (e) { 
                $("#medRecInfo").click();
            });         
    }
};